<?php

namespace PHPSpring\Utils;

class File {

  /**
   * @param string $dir
   * @param ?callable $callback
   * @param string $pattern
   * @param bool $withFullPath
   * @param string $fullPath
   * @return array
 */
  public static function readDir (string $dir, callable $callback = null, string $pattern = '', bool $withFullPath = true, string $fullPath = ''): array {
    $result = array();
    $cdir = scandir($dir);
    foreach ($cdir as $key => $value) {
      if (!in_array($value, array(".", ".."))) {
        if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) {
          $path = $value;
          if ($withFullPath && !empty($fullPath)) {
            $path = $fullPath . DIRECTORY_SEPARATOR . $value;
          }
          $result[$path] = self::readDir($dir . DIRECTORY_SEPARATOR . $value, $callback, $pattern, $withFullPath, $path);
        } else {
          if (empty($pattern) || preg_match($pattern, $value)) {
            $result[] = $value;
            if (is_callable($callback)) {
              $path = rtrim($fullPath, DIRECTORY_SEPARATOR);
              $callback($path, $value);
            }
          }
        }
      }
    }
    return $result;
  }

  public static function unifyPath(string $path, bool $postfix = true, bool $toWin = false): string
  {
    $path = rtrim($path, '/\\');
    if ($toWin) {
      $path = str_replace('/', '\\', $path).($postfix ? '\\' : '');
    } else {
      $path = str_replace('\\', '/', $path).($postfix ? '/' : '');
    }

    return $path;
  }
}
